package com.youxin.busfoundation.common;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import com.youxin.busfoundation.bean.login.PayloadBean;
import com.youxin.busfoundation.bean.login.UserInfo;
import com.youxin.busfoundation.common.login.Jwt;
import com.youxin.busfoundation.utils.web.CookieUtils;
import com.youxin.foundation.utils.StringUtils;

public class LoginAuth {

	private static final ThreadLocal<UserInfo> context = new ThreadLocal<UserInfo>();

	private LoginAuth() {
	}

	public static UserInfo getUserInfo() {
		return context.get();
	}

	public static Long getUserId() {
		UserInfo userInfo = getUserInfo();
		if (userInfo == null) {
			return null;
			// return 1l; //测试
		}
		return userInfo.getId();
	}


	/**
	 * 设置会话级别的session元素值
	 * 
	 * @param userInfo
	 */
	public static void initThreadContext(UserInfo userInfo) {
		context.set(userInfo);
	}

	/**
	 * 删除该线程本地当前线程的值变量
	 */
	public static void clear() {
		// context.set(null);
		context.remove();
	}
	
	public static String getToken(HttpServletRequest request)
	{
		String token =null;
        token=request.getHeader(GlobalConfig.TOKEN_NAME);        
		Cookie cookie=CookieUtils.getCookie(GlobalConfig.TOKEN_NAME, request);
		if(cookie!=null)
		{
			token=cookie.getValue();
		}
		return token;
	}
	
	public static PayloadBean auth(HttpServletRequest request){
        String token =getToken(request);
		return auth(token);
	}
	
	public static PayloadBean auth(String token){
		if(StringUtils.isNullOrEmpty(token))
		{
			return null;
		}
		PayloadBean payload=Jwt.validToken(token);
		return payload;
	}
	
}